<template lang="pug">
.sanpleProcess 
  data-page(
        v-bind="pageParams"
      )
      div(style="color: #bbb;margin-bottom: 10px;margin-top: 10px") 当前标本:
        el-badge(v-for="(item,index) in specimenType" :key="index" :value="item.value" :label="item.label" style="margin-left: 15px;")
          mt-button(@click="radioItemClick(item.state)" link :class="{'is-button': item.disabled,}") {{ item.label }}
        span(style="color: #ff4500;margin-left: 20px;") 提示：该列表未展示数据时，请手动点击查询！
      mt-table(
        v-bind="tableProps"
      )
sampleTrajectory(v-model="trajectoryShow" :selectionRow="specimenRow")   
printReport(:select-item="selectRow") 
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { useQuery } from "@scmt/common-hooks";
import {
  type ApiBasedOptions,
  type QueryPagination,
  useApi,
} from "@scmt/core-api";
import { type SpecimenQueryParams } from "@scmt/api-lis-specimen";
import printReport from "../components/print-report.vue";
import sampleTrajectory from "../components/sampleTrajectory.vue";

const $api = useApi();
const $notify = useNotify();
const $utils = useUtils();
const queryPramas = reactive<SpecimenQueryParams>({
  startDate: $utils.date().startOf("date").format("YYYY-MM-DD HH:mm:ss"),
  endDate: $utils.date().endOf("date").format("YYYY-MM-DD HH:mm:ss"),
  pageNum: 1,
  pageSize: 20,
});

const selectEquipment = defineModel();
const selectionRow = ref([]);
const selectRow = ref({});
const trajectoryShow = ref(false);
const specimenRow = ref({});
const buttonClass = ref("");
import { useUtils } from "@scmt/lib-utils";
import { type PatientEntity } from "@scmt/api-patient";
import {
  ESpecimenStatus,
  ESpeimenTableColumnKey,
  specimenColumns,
} from "@scmt/api-common";
const patients = ref<ApiBasedOptions<PatientEntity>>([]);

const { query, data, loadingMap } = useQuery({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.specimen.getSpecimenPageList(params);
  },
  batchGenerateBarcode: (q: any) => {
    return $api.lis.specimen.batchGenerateBarcode(q).then(() => {
      $notify.success("生成条码成功");
      query("tableData");
      query("getCountList");
    });
  },
  printBarcode: (val: string[]) => {
    return $api.lis.specimen.printBarcode(val).then(() => {});
  },
  getCountList: () => {
    return $api.lis.specimen.getCountList();
  },
  listAsOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  tubelistAsOptions: () => {
    return $api.lis.tube.listAsOptions();
  },
  patients: async (keyword: string) => {
    if (!keyword && patients.value.length) {
      return patients.value;
    }

    return $api.patient.listAsOptions({ keyword });
  },
  patientType: () => $api.dict.item.listAsOptions("patient-type"),
  listAsBedOptions: () => $api.osm.bed.listAsOptions(),
  listAsWardOptions: () => $api.osm.ward.listAsOptions(),
  loadcollectionMethod: () => $api.dict.item.listAsOptions("collection_method"),
});

const radioItemClick = (item: number) => {
  if (specimenType.value) {
    for (let i = 0; i < specimenType.value.length; i++) {
      if (specimenType.value[i].state == item) {
        specimenType.value[i].disabled = true;
      } else {
        specimenType.value[i].disabled = false;
      }
    }
  }
  queryPramas.state = item;
  query("tableData", { state: item });
};

onMounted(() => {
  query("tableData");
  query("getCountList");
  query("listAsOptions");
  query("tubelistAsOptions");
  query("patientType");
  query("listAsBedOptions");
  query("listAsWardOptions");
  query("loadcollectionMethod");
});

const specimenType = computed(() => {
  return [
    {
      label: "未生成",
      value: data.getCountList?.notGeneratedNum,
      onClick: () => {
        buttonClass;
        query("tableData", { state: ESpecimenStatus.NOTGENERATED });
      },
      disabled: false,
      state: ESpecimenStatus.NOTGENERATED,
    },
    {
      label: "已打印条码",
      value: data.getCountList?.printedNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.PrintedBarCode });
      },
      disabled: false,
      state: ESpecimenStatus.PrintedBarCode,
    },
    {
      label: "已采集",
      value: data.getCountList?.collectedNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Collection });
      },
      disabled: false,
      state: ESpecimenStatus.Collection,
    },
    {
      label: "已送检",
      value: data.getCountList?.submissionNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Submission });
      },
      disabled: false,
      state: ESpecimenStatus.Submission,
    },
    {
      label: "已签收",
      value: data.getCountList?.receiptNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Receipt });
      },
      disabled: false,
      state: ESpecimenStatus.Receipt,
    },

    {
      label: "已拒收",
      value: data.getCountList?.rejectionNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Rejection });
      },
      disabled: false,
      state: ESpecimenStatus.Rejection,
    },
    {
      label: "待审核",
      value: data.getCountList?.verificationNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Verification });
      },
      disabled: false,
      state: ESpecimenStatus.Verification,
    },
    {
      label: "已审核",
      value: data.getCountList?.examineNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.Examine });
      },
      disabled: false,
      state: ESpecimenStatus.Examine,
    },
    {
      label: "已打印报告",
      value: data.getCountList?.printedReportNum,
      onClick: () => {
        query("tableData", { state: ESpecimenStatus.PrintedReport });
      },
      disabled: false,
      state: ESpecimenStatus.PrintedReport,
    },
  ];
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "billingDepartment",
      label: "开单机构",
    },
    {
      prop: "billingDepartment",
      label: "病区",
    },
    {
      prop: "billingDepartment",
      label: "床位号",
    },
    {
      prop: "billingDepartment",
      label: "仪器",
      as: "select",
      options: {
        loadMethod: () => $api.lis.instrument.listAsOptions(),
      },
    },

    {
      prop: "patientName",
      label: "患者信息",
    },
    {
      prop: "patientName",
      label: "医保",
      as: "checkbox",
      span: 1,
    },
    {
      prop: "barcode",
      label: "条形码",
    },
    {
      prop: "applicationNumber",
      label: "申请单号",
    },
    {
      prop: "outpatientNumber",
      label: "门诊号",
    },
    {
      prop: "billingDepartment",
      label: "开单科室",
      as: "select",
      options: {
        loadMethod: () => {
          return $api.upms.org.listAsOptions();
        },
      },
    },
    {
      prop: "billingTime",
      label: "开单时间",
      as: "date",
      options: {
        type: "datetimerange",
      },
    },
    {
      prop: "specimenTypeId",
      label: "标本类型",
      as: "select",
      options: {
        loadMethod: () => {
          return $api.lis.specimen.category.listAsOptions();
        },
      },
    },
    {
      prop: "urgent",
      label: "加急",
      as: "checkbox",
      span: 1,
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    onQuery: () => query("tableData"),
    onAct: onPageActions,
    columns: 5,
    flex: true,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      specimenColumns[ESpeimenTableColumnKey.Source],
      specimenColumns[ESpeimenTableColumnKey.Barcode],
      specimenColumns[ESpeimenTableColumnKey.OutpatientNumber],
      specimenColumns[ESpeimenTableColumnKey.PatientName],
      specimenColumns[ESpeimenTableColumnKey.Sex],
      specimenColumns[ESpeimenTableColumnKey.Age],
      specimenColumns[ESpeimenTableColumnKey.ApplicationProject],
      {
        prop: "applicationNumber",
        tooltip: true,
        label: "申请单号",
      },
      specimenColumns[ESpeimenTableColumnKey.SpecimenTypeId],
      {
        prop: "tubeId",
        tooltip: true,
        label: "试管名称",
        render: ({ row }) => {
          const patientType = data.tubelistAsOptions ?? [];
          let resText = row.tubeId;
          let color = "";
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter((item) => item.value == row.tubeId);
            if (filter && filter.length > 0) {
              resText = filter[0].label;
              color = filter[0]._raw.color;
            }
          }
          return h(
            "div",
            {
              style: {
                width: "50%",
                background: color,
                marginLeft: "25%",
              },
            },
            resText
          );
        },
      },
      {
        prop: "specs",
        label: "规格",
      },
      {
        prop: "additive",
        label: "添加剂",
        minWidth: 150,
      },
      {
        prop: "collectionMethod",
        label: "采集方式",
        minWidth: 150,
        render: ({ row }) => {
          const patientType = data.loadcollectionMethod ?? [];
          let resText = row.collectionMethod;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionMethod
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "bloodCollectionVolume",
        label: "采血量",
      },
      specimenColumns[ESpeimenTableColumnKey.BillingDepartment],
      specimenColumns[ESpeimenTableColumnKey.BillingDoctor],
      specimenColumns[ESpeimenTableColumnKey.BillingTime],
      {
        prop: "patientType",
        label: "患者类型",
        tooltip: true,
        render: ({ row }) => {
          const patientType = data.patientType ?? [];
          let resText = row.patientType;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.patientType
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      specimenColumns[ESpeimenTableColumnKey.Urgent],
      {
        label: "操作",
        fixed: "right",
        actions: [
          {
            label: "查看",
            event: "check",
            type: "primary",
          },
          {
            label: "打印",
            event: "print",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) => query("tableData", pagination),
    onRowClick: (row: any) => {
      selectEquipment.value = row;
    },
    onSelectionChange: (selection: any) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "check":
      trajectoryShow.value = true;
      specimenRow.value = {};
      specimenRow.value = model;
      break;
    case "print":
      initPrintModel(model);
      break;
  }
};
//初始化打印需要的值
const initPrintModel = (model: any) => {
  selectRow.value = {};
  setTimeout(() => {
    selectRow.value = model;
  }, 500);
};
</script>

<style lang="less" scoped>
.sanpleProcess {
  :deep(.el-timeline-item__timestamp.is-top) {
    font-size: 18px;
    color: #303133;
  }
  :deep(.el-button.is-link) {
    :hover {
      color: #1c7bef;
    }
  }
  .is-button {
    color: #1c7bef;
  }
}
</style>
